<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    width="60%"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="120px"
    >
      <el-form-item label="考勤组名称：">
        <el-input v-model="dataForm.roleName" placeholder="角色名称"></el-input>
      </el-form-item>
      <el-form-item label="参与考勤人员：">
        <el-input
          v-model="dataForm.roleName"
          @focus="innerVisible = true"
          :readonly="true"
          placeholder="请选择"
        ></el-input>
      </el-form-item>
      <el-form-item label="无需考勤人员：">
        <el-input
          v-model="dataForm.roleName"
          @focus="innerVisible = true"
          :readonly="true"
          placeholder="请选择"
        ></el-input>
      </el-form-item>
      <el-form-item label="考勤组负责人：">
        <el-input
          v-model="dataForm.roleName"
          @focus="innerVisible = true"
          :readonly="true"
          placeholder="请选择"
        ></el-input>
      </el-form-item>
      <el-form-item label="考勤类型：">
        <el-radio v-model="radio" label="1">固定班制（每天考勤时间一样）</el-radio>
        <el-radio v-model="radio" label="2">排班制（自定义设置考勤时间）</el-radio>
        <el-radio v-model="radio" label="3">自由工时（不设置班次，随时打卡）</el-radio>
      </el-form-item>
      <el-form-item label="工作日设置：" prop="remark">
        <div>
          <span>快捷设置班次：班次A: 08:30-17:30</span>
          <el-button
            v-if="isAuth('sys:role:update')"
            type="text"
            size="small"
            @click="addOrUpdateHandle(scope.row.roleId)"
          >更改班次</el-button>
          <el-table
            :data="dataList"
            v-loading="dataListLoading"
            @selection-change="selectionChangeHandle"
            style="width: 100%;"
          >
            <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
            <el-table-column prop="weekL" header-align="center" align="center" label="工作日"></el-table-column>
            <el-table-column prop="timeArea" header-align="center" align="center" label="班次时间段"></el-table-column>
            <el-table-column
              fixed="right"
              header-align="center"
              align="center"
              width="150"
              label="操作"
            >
              <template slot-scope="scope">
                <el-button
                  v-if="isAuth('sys:role:update')"
                  type="text"
                  size="small"
                  @click="addOrUpdateHandle(scope.row.roleId)"
                >更改班次</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form-item>
    </el-form>
    <el-dialog width="30%" title :visible.sync="innerVisible" append-to-body>
      <el-tree
        :data="menuList"
        ref="menuListTree"
        show-checkbox
        :check-strictly="true"
        @current-change="menuListTreeCurrentChangeHandle"
        @check-change="handleCheckChange"
        :highlight-current="true"
        :expand-on-click-node="false"
      ></el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="innerVisible = false">取 消</el-button>
        <el-button type="primary" @click="innerVisible = false">确定</el-button>
      </div>
    </el-dialog>

    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { treeDataTranslate } from "@/utils";
export default {
  data() {
    return {
      visible: false,
      checked: false,
      innerVisible: false,
      value1: "",
      value2: "",
      value3: "",
      value4: "",
      radio: "1",
      dataList: [],
      totalPage: 0,
      dataListLoading: false,

      dataListSelections: [],
      menuList: [],

      dataForm: {
        id: 0,
        roleName: "",
        remark: ""
      },
      dataRule: {
        roleName: [
          { required: true, message: "角色名称不能为空", trigger: "blur" }
        ]
      },
      tempKey: -666666 // 临时key, 用于解决tree半选中状态项不能传给后台接口问题. # 待优化
    };
  },
  methods: {
    init(id) {
      this.dataForm.id = id || 0;
      this.$http({
        url: this.$http.adornUrl("/sys/org/list"),
        method: "get",
        params: this.$http.adornParams()
      })
        .then(({ data }) => {
          this.menuList = data.list;
        })
        .then(() => {
          this.visible = true;
          this.$nextTick(() => {
            this.$refs["dataForm"].resetFields();
            // this.$refs.menuListTree.setCheckedKeys([]);
          });
        })
        .then(() => {
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/sys/role/info/${this.dataForm.id}`),
              method: "get",
              params: this.$http.adornParams()
            }).then(({ data }) => {
              if (data && data.code === 0) {
                this.dataForm.roleName = data.role.roleName;
                this.dataForm.remark = data.role.remark;
                var idx = data.role.menuIdList.indexOf(this.tempKey);
                if (idx !== -1) {
                  data.role.menuIdList.splice(
                    idx,
                    data.role.menuIdList.length - idx
                  );
                }
                // this.$refs.menuListTree.setCheckedKeys(data.role.menuIdList);
              }
            });
          }
        });
      this.$http({
        url: this.$http.adornUrl("/sys/role/list"),
        method: "get",
        params: this.$http.adornParams({
          page: this.pageIndex,
          limit: this.pageSize,
          roleName: this.dataForm.roleName
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list;
          this.totalPage = data.page.totalCount;
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      });
    },
    selectionChangeHandle(val) {
      this.dataListSelections = val;
    },
    menuListTreeCurrentChangeHandle(data, node) {
      this.dataForm.parentId = data.menuId;
      this.dataForm.parentName = data.name;
    },
    handleCheckChange(data, checked, indeterminate) {
      console.log(data, checked, indeterminate);
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `/sys/role/${!this.dataForm.id ? "save" : "update"}`
            ),
            method: "post",
            data: this.$http.adornData({
              roleId: this.dataForm.id || undefined,
              roleName: this.dataForm.roleName,
              remark: this.dataForm.remark,
              menuIdList: [].concat( )
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    }
  }
};
</script>
